import { SPEED, START_DIR, START_POS } from "@/config";
import useInterval from "@/hooks/useInterval";
import { setModel, useModel } from "@/stores/models";
import { useFrame, useThree } from "@react-three/fiber";
import { RapierRigidBody } from "@react-three/rapier";
import Ecctrl from "ecctrl";
import { useEffect, useRef, useState } from "react";
import { Vector3 } from "three";
import TWEEN, { Group } from "@tweenjs/tween.js";
import { cameraLookPos } from "@/utils/model";

// 创建 TWEEN Group 实例
const tweenGroup = new Group();

const targetPosition = new Vector3(0.5, 1, 6); // 相机位置
const targetLookAt = new Vector3(0, 1, 0); // 相机朝向目标
export default function Player() {
  const camera = useThree((state) => state.camera);
  const rigidRef = useRef<RapierRigidBody>(null); //  玩家所在刚体
  const [disable, setDisable] = useState(false);
  const startAnim = useModel((state) => state.startAnim);

  const startPos = new Vector3(...START_POS);

  useEffect(() => {
    if (!rigidRef.current) return;
    rigidRef.current.setTranslation(startPos, false);
  }, [rigidRef.current]);

  useEffect(() => {
    if (!startAnim) return;
    cameraMoveTo(targetPosition, targetLookAt);
  }, [startAnim]);

  useFrame(() => {
    tweenGroup.update();
  });

  useInterval(() => {
    if (!rigidRef?.current) return;
    const pos = rigidRef.current!.translation();
    setModel({ playerPos: new Vector3(pos.x, pos.y, pos.z) });
    if (pos.y > 0) return;
    rigidRef.current.setTranslation(startPos, false);
    rigidRef.current.setLinvel({ x: 0, y: 0, z: 0 }, false);
  }, 2000);

  // 相机移动
  function cameraMoveTo(to: Vector3, target: Vector3) {
    if (!camera) return;

    setDisable(true);
    new TWEEN.Tween(camera.position, tweenGroup)
      .to(to, 1500)
      .easing(TWEEN.Easing.Quartic.InOut)
      .start()
      .onUpdate(() => {
        rigidRef.current!.setTranslation(camera.position, false);
      })
      .onComplete(() => {
        setTimeout(() => {
          setDisable(false);
          setModel({ startAnim: false });
        }, 300);
      });

    // 相机朝向变化
    const targetPosition = cameraLookPos(camera);
    new TWEEN.Tween(targetPosition, tweenGroup)
      .to(target, 1500)
      .easing(TWEEN.Easing.Quartic.InOut)
      .onUpdate(() => {
        camera.lookAt(targetPosition);
      })
      .start();
  }

  return (
    <Ecctrl
      // 人物设置
      camMoveSpeed={-1}
      camInitDir={START_DIR}
      maxVelLimit={SPEED} // 人物移动速度
      turnVelMultiplier={1}
      turnSpeed={100}
      name="player"
      // 相机设置
      camListenerTarget="document"
      camCollision={false}
      camInitDis={-0.01}
      camMinDis={-0.01}
      camMaxDis={-0.01}
      camLerpMult={1000}
      camFollowMult={1000}
      camUpLimit={Math.PI / 10}
      camLowLimit={-Math.PI / 10}
      // 移动设置
      mode="CameraBasedMovement"
      disableFollowCam={disable}
      autoBalance={false}
      floatHeight={0}
      ref={rigidRef}
    />
  );
}
